package boot.spring.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import boot.spring.mapper.UserMapper;
import boot.spring.po.User;
import boot.spring.service.UserService;

import com.github.pagehelper.PageHelper;

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 5)
@Service("userservice")
public class UserServiceImpl implements UserService {
    @Autowired
    public UserMapper userMapper;

    private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

    public User getUserById(Integer id) {
        User u = userMapper.getUserById(id);
        return u;
    }

    public User updateUser(User u) {
        userMapper.updateUserById(u);
        return u;
    }

    public List<User> getPageUsers(int pagenum, int pagesize) {
        PageHelper.startPage(pagenum, pagesize);
        List<User> l = userMapper.getAllUsers();
        return l;
    }

    public int getUserNum() {
        List<User> l = userMapper.getAllUsers();
        return l.size();
    }

    public User addUser(User u) {
        userMapper.insertUser(u);
        return u;
    }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    @Override
    public String asyncTask() {
        LOG.info("start sleep");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LOG.info("end sleep");
        return "ok";
    }

    @Async
    public String task() {
        return asyncTask();
    }

    @Override
    public List<Map<String, Object>> listUserMap() {
        return userMapper.listUserMap();
    }

    // 新增用户登录方法实现
    @Override
    public User login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        List<User> users = userMapper.selectUserByName(user);
        if (users != null && !users.isEmpty()) {
            for (User u : users) {
                if (u.getPassword().equals(password)) {
                    return u;
                }
            }
        }
        return null;
    }
}